package com.lcy.struct.memory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lcy.struct.domain.User;
import lombok.SneakyThrows;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lucongyang
 * @date Created in  14:52
 * @description
 */
public class TestTree {

    @SneakyThrows
    public static void main(String[] args) {
        String url = com.lcy.struct.bTreePlus.disk.TestTree.url;
        List<Long> set = new ArrayList<>();
        int n=18;
        for (int i = n; i > 0; i--) {
            set.add((long) (Math.random()*n));
        }
        set = set.stream().distinct().collect(Collectors.toList());
        writeToFile(url, "要插入的数据=" + set.toString());
        long a1 = System.currentTimeMillis();
        ObjectMapper objectMapper = new ObjectMapper();
        BPlusTreeEngine bPlusTreeEngine = new BPlusTreeEngine(3);
        for (Long l : set) {
            TreeNode treeNode = new TreeNode();
            BTreeIndex bTreeIndex = new BTreeIndex();
            bTreeIndex.addIndex(l);
            treeNode.setIndex(bTreeIndex);
            User user = new User();
            user.setId(l);
            user.setAge((int) (Math.random() * 100));
            user.setUsername(url.substring(0, (int) (Math.random() * url.length())));
            treeNode.setData(user);
            bPlusTreeEngine.addNode(treeNode);
            treeNode.getData();
        }
        long a2 = System.currentTimeMillis();
        System.out.println("插入耗时：" + (a2 - a1) + "毫秒");
        try {
            if (set.size()<100){
                System.out.println(objectMapper.writeValueAsString(bPlusTreeEngine.getRoot()));
            }
            writeToFile(url, "\n结果=" + objectMapper.writeValueAsString(bPlusTreeEngine.getRoot()));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        writeToFile(url, "\n\n\n");
        System.out.println();
    }

    private static void writeToFile(String fileUtrl, String str) {
        try {
            File file = new File(fileUtrl);
            if (!file.exists()) {
                boolean newFile = file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fileWriter);
            bw.write(str);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
